<template>
    <!-- 组件的模板 -->
  <div class="page">
        <form>
            <div class="item flex">
                <input v-on:input="veriryPhoneFormat" v-model="formData.phone" id="regiPhone" type="tel" maxlength="11" placeholder="手机号" @change = "checkNumber(formData.phone)" :value="formData.phone">
            </div>
            <div class="item flex" :class="{'active': pwdIsVisiable}">
                <input v-show="!pwdIsVisiable" v-model="formData.password" id="regiPwd" type="password" placeholder="密码（6-20个字符）" :value="formData.password">
                <input v-show="pwdIsVisiable" v-model="formData.password" id="regiPwd" type="text" placeholder="密码（6-20个字符）" :value="formData.password">
                <span class="bg_sprite icon_eye" @click="switchPwdVisiable"></span>
            </div>
            <div class="item flex">
                <input v-model="formData.vCode" id="regiVcode" type="tel" class="input-text" maxlength="6" placeholder="验证码（6位）" :value="formData.vCode">
                <span v-if="formData.phone&&formData.password" class="get-code flex active" @click="getVCode" v-show="!isCounting" id="getvCode">{{countingTxt}}</span>
                <span v-else class="get-code flex" @click="getVCode" :disabled="!vCodeActive"  v-show="!isCounting" id="getvCode">{{countingTxt}}</span>
                <span v-else class="get-code flex" @click="getVCode"  v-show="isCounting" :disabled="isCounting">{{countingTxt2}}</span>
            </div>
            <template v-if="isRegister">              
              <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_primary" @click="doRegister" v-if = "formData.phone && formData.password && formData.vCode">注 册</a>            
              <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_disabled weui-btn_primary" v-else>注 册</a>
            </template>
            <template v-if="!isRegister">              
              <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_primary" @click="doResetpwd" v-if = "formData.phone && formData.password && formData.vCode">注 册</a>
              <a href="javascript:;" id="registerBtn" class="weui-btn weui-btn_disabled weui-btn_primary" v-else>注 册</a>
            </template>
        </form>
        <p class="footer-tip">注册登录即代表同意<a href="javascript:;" @click="goAgreement">《用户注册与隐私保护服务协议》</a></p>
  </div> 
  <!-- popup start -->
  <div class="mod-popup popup-register-guide" v-show="showRegisterPopup">
    <div class="mod-popup-head hide">手机号码已注册</div>
    <div class="mod-popup-body">
      <div class="register-state">
        <span class="state-registered">已注册</span>
      </div>
      <div class="mod-popup-text">
        <p>该手机号已注册斗米</p>
        <p>请直接登录</p>
      </div>
      <div class="mod-popup-btn-box">
        <a class='btn btn-primary btn-large js-touch-state' href='dmsaas://login'>去登录</a>
        <button @click="cancelRegisterPopup" id="registered" class="btn btn-link btn-large js-touch-state">取消</button>
      </div>
    </div>
  </div>
  <div class="mod-popup popup-robot-check" v-show="showRobotPopup">
    <div class="mod-popup-head hide">确认你不是机器人</div>
    <div class="mod-popup-body">
      <div class="robot-avatar"></div>
      <div class="form-tips">请输入图片验证码确认你不是机器人：</div>
      <div class="form-field">
        <div class="form-item">
          <label class="form-label">验证码</label>
          <div class="form-control">
            <div class="multi-group">
              <label class="input-group">
                <input v-model="imgCode" id="picCode" type="text" class="input-text" placeholder="请输入验证码">
              </label>
              <div class="code-group">
                <img id="verify_code_image" v-bind:src="base64ImgData" alt=""><i @click="refreshImg" class="icon-refresh">刷新</i>
              </div>
            </div>
          </div>
        </div>
        <div class="form-warning-picode" v-show="invalidImgCode">{{imgCodeErrMsg}}</div>
      </div>
      <div class="mod-popup-btn-box">
        <button @click="submitImgCode" id="picCodeSureBtn" class="btn btn-primary btn-large js-touch-state">确认</button>
        <button @click="cancelRobotPopup" id="picCodeCancelBtn" class="btn btn-link btn-large js-touch-state">取消</button>
      </div>
    </div>
  </div>
  <div class="mask" v-show="showRobotPopup || showRegisterPopup "></div>
  <!-- <div class="form-warning" v-show="hasError">{{errMsg}}</div> -->
  <!-- popup end -->
  <!-- toast start -->
  <!-- <div class="mod-toast">
    <span>你获取验证码次数太多了
      <br>请稍后再试</span>
  </div> -->
  <!-- <div class="mod-toast">
    <span>你获取验证码太快了
      <br>请稍后再试</span>
  </div> -->
  <!--<div id="loadingToast" v-show="loading">
    <div class="weui-mask_transparent"></div>
    <div class="weui-toast">
        <i class="weui-loading weui-icon_toast"></i>
        <p class="weui-toast__content"></p>
    </div>
  </div>-->
</template>

<script>
    let receiveImgcode = true
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import $ from 'zepto'
    import userCenterApi from 'clientApi/userCenterApi'
    import clientInfo from 'gapi/clientInfo'
    import safety from 'gapi/safety'
    import widget from 'gapi/widget.js'
    import util from 'clientApi/util'  
    import * as _util from 'js/util.js'
    import commonPage from 'clientApi/commonPage.js'
    
    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */
    
    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        data: function(){
            return{
                formData: {},
                pwdIsVisiable: false,
                showRobotPopup: false,
                // showRegisterPopup: false,
                // hasError: false,
                // errMsg: '',
                vCodeActive: false,
                base64ImgData: '',
                invalidImgCode: false,
                imgCodeErrMsg: '',
                loading: false,
                imgCode: '',
                isCounting: false,
                countingTxt: '获取验证码',
                countingTxt2: '',
                mobile: '',
                isRegister: true
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){},
            /**
            * 判断手机号是否注册过----否，正常注册；是，执行重置密码
            **/
            checkNumber (mobile){
                _util.ajax({
                    url:'/group/doumi_member_exists',
                    type:'GET',
                    data:{
                        mobile:mobile
                    },
                    timeout:10000,
                    success:(obj) => {
                        console.log(JSON.stringify(obj))
                        if(obj.errno == 0){
                            this.isRegister = false  // 注册过
                        }else{
                            this.isRegister = true   // 没有
                        } 
                    },
                    error: (xhr, status) => {
                        widget.toast('服务器异常')
                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            getHost (){
              userCenterApi.getHost((data) => {
                return data.info
              })
            },
            /**
            * 监听验证手机格式, 激活手机验证码按钮
            **/
            veriryPhoneFormat () {
                const phone = this.formData.phone;
                const phoneIsValid = /^\d{11}$/.test(phone);
                this.vCodeActive = phoneIsValid ? true : false;
            },
            /**
            * 切换密码可见
            **/
            switchPwdVisiable (){
                this.pwdIsVisiable = !this.pwdIsVisiable;
            },
            /**
            * 获取手机验证码
            **/
            getVCode (){
                if(!receiveImgcode){
                    return
                }
                receiveImgcode = false

                //防止双击事件
                setTimeout(function(){
                  receiveImgcode = true
                }, 1000)

                this.vCodeActive = false
                let apiUrl = "";
                let headers = {}
              
                clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + util.getApiPath() + '/authCkCode'//todo:encapsule
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'POST',
                          dataType: 'json',
                          data: {
                            mobile: this.formData.phone,
                            platform: util.OS(),
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {//手机验证码发送成功
                            this.isCounting = true; //show countdown button
                            this.countDown(60); //counting down
                          },
                          error: (xhr, status) => {
                            if (status == 'timeout'){
                              widget.toast('网络请求超时');
                            }else{
                                  if(xhr.status==400){                                     
                                      let err=JSON.parse(xhr.responseText);
                                      if(err.code===-3){//显示图片验证码浮层                           
                                        userCenterApi.showCodeDialog(this.formData.phone, data => {
                                          // receiveImgcode = false
                                          if(data.status == 1){ 
                                            this.isCounting = true; 
                                            this.countDown(60);                           
                                          }
                                        })
                                        // this.showRobotPopup = true
                                        // //reset 
                                        // this.invalidImgCode = false
                                        // this.imgCode = ''
                                        // this.base64ImgData = ''
                                        // // util.commonOptions(t,clientInfo,t.getPic,picData[1]);
                                        // this.getCaptcha()//获取图片验证码
                                      }else{
                                          widget.toast(err.message);
                                          
                                      }
                                  }else{
                                      this.vCodeActive = true;
                                      widget.toast('服务器异常');
                                  }
                              }
                          }
                       })  
                      })
                      
                    })
                  } else {
                    this.vCodeActive = true;
                    widget.toast('网络连接失败，请检查网络')
                  }
                })
            },
            /**
            * 获取图片验证码图片
            **/
            getCaptcha (){
                let apiUrl = ""//todo 
                let headers = {}
               clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + util.getApiPath() + '/ajax/encodedcode'
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'GET',
                          dataType: 'json',
                          data: {
                            platform: util.OS(),
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {
                            if(!!data && !!data.pic_code){
                              this.base64ImgData = data.pic_code
                        }else{
                            widget.toast('服务器异常');
                        }
                          },
                          error: (xhr, status) => {
                            // util.ajaxErrorFn(widget,xhr,status,true,UCApi);
                          }
                       })  
                      })
                      
                    })
                  } else {
                      widget.toast('网络连接失败，请检查网络');
                  }
                })
            },
            /**
            * 刷新图片验证码
            **/
            refreshImg (){
              this.getVCode()
            },
            /**
            * 提交图片验证码
            **/
            submitImgCode (){
              let apiUrl = ""
              let headers = {}
              this.invalidImgCode = false
              if(!this.imgCode){
                this.invalidImgCode = true
                this.imgCodeErrMsg = '请输入正确的图片验证码'
                return;
              }
                clientInfo.getNetworkType(data => {
                  if (data.network != 'invalid') {
                    userCenterApi.getHost(data => {
                      apiUrl =  data.info + util.getApiPath() + '/authCkCode'//todo:encapsule
                      console.log('提交图片验证码'+apiUrl)
                      clientInfo.getCommonHeaders(data => {
                        headers = data;
                        $.ajax({
                          url: apiUrl ,
                          type: 'POST',
                          dataType: 'json',
                          data: {
                            mobile: this.formData.phone,
                            platform: util.OS(),
                            code : this.imgCode,
                            token: ''
                          },
                          timeout: 10000,
                          headers: headers,
                          success: data => {//图片验证码
                            // this.showRobotPopup = false;
                            this.isCounting = true; 
                            this.countDown(60); 
                          },
                          error: (xhr, status) => {
                            if (status == 'timeout'){
                              widget.toast('网络请求超时');
                            }else{
                                  if(xhr.status==400){
                                    //xhr.responseText.code : -4 -> 图片验证码错误; -206: 一分钟内不能获取验证码  
                                    this.invalidImgCode = true
                                    this.imgCodeErrMsg = JSON.parse(xhr.responseText).message
                                  }else{
                                      widget.toast('服务器异常');
                                  }
                              }
                          }
                       })  
                      })
                      
                    })
                  } else {
                    widget.toast('网络连接失败，请检查网络');
                  }
                })
            },
            /**
            * 点击取消按钮, 关闭图片验证码弹框
            **/
            cancelRobotPopup (){
              this.showRobotPopup = false;
              this.vCodeActive = true;
            },
            /**
            * 点击取消按钮, 关闭去登录弹框
            **/
            cancelRegisterPopup (){
              this.mask = false
              // this.showRegisterPopup = false;
            },
            /**
            * 倒计时
            **/
            countDown (seconds){
              this.isCounting = true
              this.countingTxt2 = ''
              let _seconds = seconds;
              let tId;
              receiveImgcode = false
              tId = setInterval(() => {
                if (_seconds == 0){
                  clearInterval(tId);
                  this.isCounting = false
                  this.countingTxt = '重新获取'
                  this.vCodeActive = true;
                  receiveImgcode = true
                }else{
                  _seconds--;
                  this.countingTxt2 = `${_seconds}秒后重发`
                }
              }, 1000)
            },
            /**
            * 提交注册表单
            **/
            doRegister (){
                // this.hasError = true;
                //表单校验 todo: migrate to vue-validator
                if (!this.formData.phone){
                    widget.toast('请输入手机号') 
                    return
                }else if (this.formData.phone.length != 11){
                    widget.toast('请输入正确的手机号')
                    return
                }else if (!this.formData.password){
                    widget.toast('密码不能为空') 
                    return
                }else if (this.formData.password.length < 6 || this.formData.password.length > 12){
                    widget.toast('密码长度6—12个字符')
                    return
                }else if (/^(\d+)$/.test(this.formData.password)){ //纯数字
                    widget.toast('密码不能是纯数字')
                    return                    
                }else if (/^([a-z])\1+$/.test(this.formData.password)){ //单一重复字符
                    widget.toast('密码不能是单一重复字符')
                    return                    
                }else if (/\s/g.test(this.formData.password)){ //有空格
                    widget.toast('密码不能包含空格') 
                    return                    
                }else if (/[\u4e00-\u9fa5]/.test(this.formData.password)){ //有中文
                    widget.toast('密码不能包含中文')
                    return                    
                }else if (!this.formData.vCode){ 
                    widget.toast('验证码不能为空')
                    return                    
                }else if (!/^\d{6}$/.test(this.formData.vCode)){ //非6位数字 
                    widget.toast('验证码错误')
                    return                    
                } else {
                    // this.hasError = false
                    // this.errMsg = ""
                    this.loading = true
                    //调用客户端加密Api todo 变量作用域
                    safety.dekEncrypt(this.formData.password, info => {
                      const encryptPwd = info;
                      //调用客户端注册Api
                      userCenterApi.register(this.formData.phone, this.formData.vCode, encryptPwd, {}, data => {
                        this.loading = false
                        //1 验证码错误 2 已注册
                        // if(data.code == -310){
                        //   this.showRegisterPopup = true
                        // }else if(data.code == -205){
                          if(data.code == -205){
                          widget.toast('验证码错误')
                        } else if (data.code == 0) {
                          widget.toast('网络连接失败，请检查网络');
                        }
                      })
                    })
              }
            },
            //前往用户协议
            goAgreement (){
              clientInfo.getHost((host) => {
                let url = '/sea/api/1.0/client/v1/protocol/agreement/get?dmclient=pcweb&X-Doumi-Agent=weixinqy'
                let jump_url = host.info + url
                location.href =  `dmsaas://dmbrowser/${encodeURIComponent(jump_url)}?shareButtonHide=1`;
              })
              
            },
                 /**
            * 提交注册表单
            **/
            doResetpwd (){
                // this.hasError = true;
                //表单校验 todo: migrate to vue-validator
                if (!this.formData.phone){
                    widget.toast('请输入手机号')
                    return
                }else if (this.formData.phone.length != 11){
                    widget.toast('请输入正确的手机号')
                    return
                }else if (!this.formData.password){
                    widget.toast('密码不能为空') 
                    return
                }else if (this.formData.password.length < 6 || this.formData.password.length > 12){
                    widget.toast('密码长度6—12个字符')
                    return
                }else if (/^(\d+)$/.test(this.formData.password)){ //纯数字
                    widget.toast('密码不能是纯数字')
                    return                    
                }else if (/^([a-z])\1+$/.test(this.formData.password)){ //单一重复字符
                    widget.toast('密码不能是单一重复字符')
                    return                    
                }else if (/\s/g.test(this.formData.password)){ //有空格
                    widget.toast('密码不能包含空格')
                    return                    
                }else if (/[\u4e00-\u9fa5]/.test(this.formData.password)){ //有中文
                    widget.toast('密码不能包含中文')
                    return                    
                }else if (!this.formData.vCode){ 
                    widget.toast('验证码不能为空')
                    return                    
                }else if (!/^\d{6}$/.test(this.formData.vCode)){ //非6位数字 
                    widget.toast('验证码错误')
                    return                    
                } else {
                    // this.hasError = false
                    // this.errMsg = ""
                    this.loading = true
                    let apiUrl = ""
                    let headers = {}
                    //调用客户端加密Api todo 变量作用域
                    commonPage.loadPageStatus('loading')
                    safety.dekEncrypt(this.formData.password, info => {
                      const encryptPwd = info;
                      //请求服务端接口
                      clientInfo.getNetworkType(data => {
                        if (data.network != 'invalid') {
                          userCenterApi.getHost(data => {
                            apiUrl =  data.info + util.getApiPath() + '/reset'
                            clientInfo.getCommonHeaders(data => {
                              headers = data;
                              $.ajax({
                                url: apiUrl ,
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                  mobile: this.formData.phone,
                                  code : this.formData.vCode,
                                  password: encryptPwd
                                },
                                timeout: 10000,
                                headers: headers,
                                success: data => {
                                  commonPage.loadPageStatus('loadSuccess')
                                  // widget.toast('重置密码成功')
                                  // window.location.href='dmsaas://ProjectList' 
                                      //调用客户端加密Api todo 变量作用域
                                  safety.dekEncrypt(this.formData.password, info => {
                                    const encryptPwd = info;
                                    //调用客户端登陆Api
                                    userCenterApi.logIn(this.formData.phone, '', encryptPwd, {}, data => {
                                      // if(!!data){                   
                                      //   console.log("errorMessage"+data.code);
                                      //   if (data.code == -201) {
                                      //     widget.toast(data.message);
                                      //   }else if(data.code == -313) {
                                      //     widget.toast('当前用户未注册，请直接注册');
                                      //   }else if(data.code == -312) {
                                      //     widget.toast('密码错误，请点忘记密码进行重置');
                                      //   }else{
                                      //     widget.toast(data.message);
                                      //   }
                                      // }
                                      // Native toast: 密码错误 or  未注册
                                    })
                                  })

                                },
                                error: (xhr, status) => {
                                  commonPage.loadPageStatus('loadSuccess')
                                  if (JSON.parse(xhr.responseText).code == -205) { //验证码错误
                                    // $('.form-warning').text('验证码错误').fadeIn();
                                    widget.toast('验证码错误')
                                  } else{
                                    widget.toast(JSON.parse(xhr.responseText).message)
                                  }
                                }
                            })  
                            })
                          })
                        }else{//无网
                          commonPage.loadPageStatus('loadSuccess')
                          widget.toast('网络连接失败，请检查网络');
                        }
                })
                      /*userCenterApi.register(this.formData.phone, this.formData.vCode, encryptPwd, {}, data => {
                        this.loading = false
                        //1 验证码错误 2 未注册 
                        //success -> login page 
                      })*/
                    })
              }
            }
        },
        created(){

            this.init();
            
        }
        
    }

    
</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/global.css"></style>
<style src="../../static/css/login.css"></style>
<style src="../../static/css/form.css"></style>
<style src="../../static/css/account.css"></style>
<style src="../../static/css/common.css"></style>
<style src="../../static/css/login-register.css"></style>
<style>
  body{
    background: #fff!important;
  }
  .input-text{
    text-align: left!important;
  }
  ::-webkit-input-placeholder {
    color: #bbb!important;
  }
  .dialog__btn_primary {
    color: black!important;
  }

</style>



